package com.huike.service;

import com.huike.dao.GroupDAO;
import com.huike.dao.PartDAO;
import com.huike.dao.UserDAO;
import com.huike.po.Employee;
import com.huike.po.GroupWithOwnerAccount;
import com.huike.po.Part;
import com.huike.po.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PartServiceImpl implements PartService {
    @Autowired
    private PartDAO partDAO;
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private GroupDAO groupDAO;

    @Autowired
    private GroupWithOwnerAccount group;


    @Override
    public boolean addEmployeeToPart(int partId, int employeeId) {
        boolean res = partDAO.updateEmployeePart(employeeId, partId);
        return res;
    }

    @Override
    public boolean deleteEmployeeFromPart(int employeeId) {
        boolean res = partDAO.deleteEmployeePart(employeeId);
        return res;
    }

    @Override
    public List<Part> getPartList() {
        List<Part> partList = partDAO.selectAllPartInfo();
        for(Part pt : partList){
            List<Employee> employeeList = pt.getEmployeeList();
            for (Employee employee: employeeList) {
                String account = employee.getAccountInfo().getAccount();
                UserDetail employeeInfo = userDAO.selectUserDetailByAccount(account);
                employee.setAccountInfo(employeeInfo);
            }
        }


        return partList;
    }

    @Override
    public List<Part> getPartListByName(String name) {
        List<Part> partList = partDAO.selectPartByName(name);
        for(Part pt : partList)
            pt.getEmployeeList();
        return partList;
    }

    @Override
    public Part getPartById(int id) {
        Part part = partDAO.selectPartById(id);
        List<Employee> emList = part.getEmployeeList();
        for(Employee e : emList)
            System.out.println(e.getPartId());
        return part;
    }

    @Override
    public boolean addPart(int partId,String partName, int managerId, int partLevel) {
        boolean res = partDAO.insertPart(partId,partName, managerId, partLevel);
        // 搜索对应的employee记录
        Employee employee  =partDAO.selectEmployeeByID(managerId);
        group.setGroupName(partName);
        group.setAccount(employee.getAccountInfo().getAccount());
        // 创建对应的部门组织群
        groupDAO.createOrganizationGroup(group);
        return res;
    }

    @Override
    public boolean deletePart(int partId) {
        boolean res = partDAO.deletePart(partId);
        return res;
    }

    @Override
    public boolean updatePart(Part part) {
//        int id = part.getPartId();
//        Part oPart = partDAO.selectPartInfoByID(id);
        boolean res = partDAO.updatePartInfo(part);
        return res;
    }


}
